package com.tiancheng.trade.settlement.task;

import com.tiancheng.trade.commom.core.utils.DateTimeUtil;
import com.tiancheng.trade.settlement.exception.BusinessException;
import com.tiancheng.trade.settlement.exception.error.BusinessErrorInfoEnum;
import com.tiancheng.trade.settlement.service.settlement.SettleCheckService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * 每日自动对账任务
 *
 * @author kellen
 * @date 2021/3/26
 */
@Slf4j
@Component
public class DallySettleCheckTask {
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private SettleCheckService settleCheckService;

    /**
     * 自动对账任务
     * -每日生成前一日对账结果，若对应回盘文件还未返回，则参与后续对账
     *
     * @param param String
     * @return Result<String>
     */
    @XxlJob("doSettleCheck")
    public ReturnT<String> doSettleCheck(String param) {
        log.info("自动对账任务开始：{}", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        RLock lock = redissonClient.getLock("SETTLEMENT_DO_SETTLE_CHECK");
        boolean isLock;
        try {
            isLock = lock.tryLock(30L, TimeUnit.MINUTES);
            if (!isLock) {
                log.error("自动对账任务执行结果：锁失败！");
                return ReturnT.SUCCESS;
            }
            LocalDate date=null;
            if(StringUtils.isNotEmpty(param)){
                date= DateTimeUtil.formatDate(param,"yyyy-MM-dd");
            }

            settleCheckService.clearCheck(date);
        } catch (Exception e) {
            log.error("自动对账任务执行失败：{}", e.getMessage(),e);
            throw new BusinessException(BusinessErrorInfoEnum.DO_SETTLE_CHECK_ERROR, null, "自动对账任务执行失败", e);
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
        log.info("自动对账任务执行结束：{}", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return ReturnT.SUCCESS;
    }

}
